/**
 * Huisou.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */

package com.chenzehe.hadoop.action;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

/**
 * @description
 * 
 * @author chenzehe
 * @email hljuczh@163.com
 * @create 2013-8-5 下午06:43:46
 */

public class STjoin {
	public static int	time	= 0;
	
	public static class Map extends Mapper<Object, Text, Text, Text> {
		public void map(Object key, Text value, Context context) {
			String childname = new String();
			String parentname = new String();
			String relationtype = new String();
			
			String line = value.toString();
			int i = 0;
			while (line.charAt(i) != ' ') {
				i++;
			}
			String[] values = { line.substring(0, i), line.substring(i + 1) };
			if (values[0].compareTo("child") != 0) {
				childname = values[0];
				parentname = values[1];
				relationtype = "1";
				try {
					context.write(new Text(parentname), new Text(relationtype + "+" + childname + "+" + parentname));
				}
				catch (Exception e) {
					// TODO Auto-generated catch block
				}
				relationtype = "2";
				try {
					context.write(new Text(childname), new Text(relationtype + "+" + childname + "+" + parentname));
				}
				catch (Exception e) {
					// TODO Auto-generated catch block
				}
			}
		}
	}
	
	public static class Reduce extends Reducer<Text, Text, Text, Text> {
		public void reduce(Text key, Iterable<Text> values, Context context) {
			String output = "";
			for (Text value : values) {
				output += value + "*";
			}
			try {
				context.write(key, new Text(output));
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
		if (otherArgs.length != 2) {
			System.err.println("Usage: stjoin <in> <out>");
			System.exit(2);
		}
		Job job = new Job(conf, "my stjoin");
		job.setJarByClass(STjoin.class);
		job.setMapperClass(Map.class);
		// job.setCombinerClass(ReduceClass.class);
		job.setReducerClass(Reduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
		FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
